<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="closeDialog" v-on:open="loadData" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-form">
      <!--  -->
        <el-row>
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">摄像头</div>
            <div style="text-align: center;padding:2px;">
              <video id="video" width="200px" height="150px" autoplay ></video>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8" style="padding-left:5px;">
          <el-card class="box-card">
            <div slot="header" class="clearfix">照片</div>
            <div style="text-align:center;padding:2px;">
              <canvas id="canvas"  style="width:200px;height: 150px;"></canvas>
              <!-- <img src="/static/img/man.png" v-show="photo=true" height="150px"> -->
            </div>
          </el-card>
        </el-col>
        </el-row>
        <div class="divBUtton">
          <el-button type="primary" @click="matchSubjectFace" >拍照</el-button>
        </div>
        
         <!--  -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色"  prop="roleIds">
              <el-select v-model="form.roleIds" placeholder="请选择角色"   multiple>
                <el-option
                  v-for="item in roleList"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中心">
              <el-select v-model="form.siteId" placeholder="请选择中心"  >
                <el-option
                  v-for="item in siteList"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="帐号" prop="account">
          <el-input v-model="form.account" :readonly="form.id!=undefined&&form.id!=''"></el-input>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="不修改密码可以留空"></el-input>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio class="radio" v-model="form.sex" :label="1">男</el-radio>
              <el-radio class="radio" v-model="form.sex" :label="0">女</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="说明">
          <el-input type="textarea" v-model="form.remark" style="width: 91%"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="active">
          <el-radio class="radio" v-model="form.active" :label="1">启用</el-radio>
          <el-radio class="radio" v-model="form.active" :label="0">禁用</el-radio>
        </el-form-item>
        <el-form-item class="button-row">
          <el-button v-if="$utils.ckUIPower('S01010101')" type="primary" @click.native.prevent="handleSubmit">立即创建</el-button>
          <el-button v-if="$utils.ckUIPower('S01010101')" @click.native.prevent="handleReset">重置</el-button>
          <el-button @click.native.prevent="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import http from '../../../api/http'
  var model = {
    name: '',
    account: '',
    active: 1,
    password: '',
    mobile: '',
    roleName: '',
    siteId: '',
    avator: '',
    roleIds: [],
    remark: '',
    id: '',
    sex: 1,
    errMsg:'',
    photo:false,
    context: null,
    video: null,//设备摄像头
    Imgface:'',
    face:'',

  };
  export default {
    components: {},
    data () {
      return {
        title: '用户添加', form: Object.assign({}, model),
        rules: {
          name: [
            {required: true, message: '请输入姓名'},
            {min: 1, max: 20, message: '长度在 1 到 20 个字符'}
          ],
          account:[
            {required:true,message:'请输入帐号'},
            {min:1,max:20,message:'长度在1 到 20 个字符'}
          ],
          roleIds:[
            {required:true,message:'请选择角色'}
          ],
        }, roleList: [], addBtnTxt: '',
        siteList: []
      }
    },
    props: {
      dialogFormVisible: {
        type: Boolean,
        default: false
      },
      siteId:{
          type:String,
          default:false
        }
    },
    computed: {
      dialogVisible: {
        get: function () {
          if (this.siteId != undefined) {
            this.form.siteId = this.siteId;
          }
            return this.dialogFormVisible
        },
        set: function () {}
      }
    },
    methods: {
      openVideo() {
        var vm = this;

        vm.video = vm.$el.querySelector("#video");

        var canvas = vm.$el.querySelector("#canvas");

        vm.context = canvas.getContext("2d");
        //获取摄像头对象
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

        navigator.getUserMedia({
          video: true,    // 控制视频设备
//          audio: true  // 控制音频设备
        }, gotStream, noStream); //打开摄像头
        //成功打开摄像头
        function gotStream(stream) {
          vm.mediaStream = stream;//获取视频输入输出流
          vm.video.src = URL.createObjectURL(stream);
          vm.video.onerror = function () {
            stream.stop();
          }
          stream.onended = noStream;
          vm.video.onloadedmetadata = function () {
//            alert("成功打开摄像头")
          };
        }

        //打开摄像头失败
        function noStream(error) {
//          vm.$message.error({message: '开启摄像头异常！'});
          vm.errMsg = "开启摄像头异常！";
        }
      },
      matchSubjectFace(oldImg, newImg){
        this.context.drawImage(video, 0, 0, 300, 150);
        // 获取base64位格式的图片
        // var imgstr = canvas.toDataURL();
        
        var vm = this;
        vm.errMsg = "";
        vm.form.face=canvas.toDataURL();
      },
      //////////////////////////////////////////////
      handleReset () {
        this.$refs.form.resetFields()
      },
      handleSubmit (ev) {
        var vm = this;
        this.$refs.form.validate(function (valid) {
          if (valid) {
            //设置角色名称
            var roleIds = vm.form.roleIds;
            if (roleIds != undefined && roleIds.length > 0) {
              vm.form.roleName = "";
              vm.roleList.forEach(function (r) {
                if (roleIds.indexOf(r.id) >= 0) {
                  vm.form.roleName += " " + r.name;
                }
              });
            } else {
              vm.form.roleName = "";
            }

            http.postData(vm, "/sys/account/save", {json: JSON.stringify(vm.form)}, function (resp) {
              if(vm.form.roleIds == ''||vm.form.roleIds == undefined){
                  return vm.$notify.error({title: '操作失败', message: '用户不能为空！'});
              }
              var ret = resp.body;
              if (ret.code === '111') {
                vm.$notify({title: '操作提示', message: ret.msg, type: 'success'});
                vm.form = Object.assign({}, model);
                vm.closeDialog();
                vm.$parent.onSubmit();
              } else {
                vm.$notify.error({title: '操作失败', message: ret.msg});
              }
            });
          } else {
            return false
          }
        })
      },
      closeDialog(){
        this.context.clearRect(0, 0, 300, 150);

        this.$emit('closeDialog');
        this.mediaStream.getVideoTracks()[0].stop();
      },
      loadData(){
        var vm = this;
        setTimeout(function () {
          vm.openVideo();
        }, 300);
//        vm.$parent.loadData(function (ret) {
//          if (ret != undefined) {
//            vm.form = ret;
//          } else {
//            vm.form = Object.assign({}, model);
//          }
//          if (vm.form.id == undefined || vm.form.id == '') {
//            vm.addBtnTxt = '立即创建';
//            vm.title = '用户创建';
//          } else {
//            vm.addBtnTxt = '保存修改';
//            vm.title = "用户修改"
//          }
//        });
        http.postData(vm, "/sys/role/list", {}, function (resp) {
          vm.roleList = resp.body.value;
        });
        http.postData(vm, "/pt/site/list", {}, function (resp) {
          vm.siteList = resp.body.value;
        });
      }
    }, created() {
      var vm = this;
      
    }
  }
</script>
<style>
    .divBUtton{
      margin:10px 0;
      text-align: center;
    }
</style>
